package main

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"shortUrl/controllers"
	"shortUrl/logic"
	"shortUrl/pkg/shortcode"
	"shortUrl/routers"
	"shortUrl/services/mysql"
	"shortUrl/services/redis"
	"shortUrl/setting"
	tasks "shortUrl/task"

	"github.com/gin-gonic/gin"
)

func main(){
	// 配置初始化
	if err := setting.Init();err != nil{
		fmt.Println("初始化错误")
	}
	conf := setting.Conf
	//mysql初始化
	if err := mysql.Init(*conf.MysqlConfig);err != nil{
		fmt.Println("mysql初始化错误")
	}
	
	addr := fmt.Sprintf("%s:%d",conf.RedisConfig.Host,conf.RedisConfig.Port)
	redisCache, err := redis.NewRedisCache(
		addr,
		conf.RedisConfig.Password,
		conf.RedisConfig.DB,
		conf.RedisConfig.PoolSize,
		conf.RedisConfig.MinidleConns,
	)
	if err != nil{
		fmt.Printf("err%v",err)
	}
	service := mysql.NewServiceUrl()
	shortCode := shortcode.NewShortCode()
	logic := logic.NewLoginUrl(service,shortCode,redisCache,1,"http://113.44.165.94:8080")
	ctrl := controllers.NewContraollerUrl(logic)
	// 路由初始化
	tasks.StartCleanupTask(service, conf.CleanupCron)
	r := gin.Default()
	routers.Init(r, ctrl)
	srv := &http.Server{
		Addr: "0.0.0.0:8080",
		Handler: r,
	}

	
	go func(){
		if err := srv.ListenAndServe();err != http.ErrServerClosed{
			fmt.Print(err,"err")
		}
	}()
	// 优雅启停
	quit := make(chan os.Signal,1)
	signal.Notify(quit, syscall.SIGINT,syscall.SIGTERM)
	<- quit
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx);err != nil{
		fmt.Print(err,"err")
	}
}
